// components/activation-code-popup/activation-code-popup.js
const app = getApp();
const { request } = require('../../utils/request.js');
const api = require('../../utils/api.js');

Component({
  properties: {
    visible: {
      type: Boolean,
      value: false
    },
    userInfo: {
      type: Object,
      value: null
    }
  },

  data: {
    activationCode: '',
    inputFocused: false,
    isActivating: false,
    resultMessage: '',
    resultType: 'success' // 'success' 或 'error'
  },

  lifetimes: {
    attached() {
      this.ensureLogin();
    },
    ready() {
      // 预加载组件，避免渲染跳动
      this.preloadRender();
    }
  },

  methods: {
    // 预加载渲染
    preloadRender() {
      // 这个方法不做任何事情，只是确保组件在显示前已经被完全渲染
    },

    // 关闭弹窗
    closePopup() {
      this.setData({
        visible: false,
        activationCode: '',
        resultMessage: '',
        isActivating: false,
        inputFocused: false,
        resultType: 'success'
      });
      this.triggerEvent('close');
    },

    // 输入框内容变化
    onInputChange(e) {
      this.setData({
        activationCode: e.detail.value
      });
    },

    // 输入框获得焦点
    onInputFocus() {
      this.setData({
        inputFocused: true
      });
    },

    // 输入框失去焦点
    onInputBlur() {
      this.setData({
        inputFocused: false
      });
    },

    // 提交激活码
    submitCode() {
      const code = this.data.activationCode.trim();
      if (!code) {
        wx.showToast({
          title: '请输入激活码',
          icon: 'none'
        });
        return;
      }

      // 显示加载中
      wx.showLoading({
        title: '激活中',
      });

      // 设置激活中状态
      this.setData({
        isActivating: true,
        resultMessage: ''
      });

      // 发送请求
      request(api.activate_code, 'POST', {
        user_id: this.properties.userInfo.user_id,
        code: code
      })
        .then(res => {

          // 激活成功
          this.setData({
            resultType: res.code === 0?'error':'success',
            resultMessage: res.msg
          });

          if (res.data) {
            // 更新用户信息中的使用次数
            const updatedUsageCount = res.data.usage_count;
            const addedCount = res.data.added_count;

            // 更新组件内数据
            this.setData({
              'userInfo.usage_count': updatedUsageCount
            });

            // 更新全局数据
            app.globalData.userInfo.usage_count = updatedUsageCount;

            // 触发成功事件
            this.triggerEvent('success', {
              usage_count: updatedUsageCount,
              added_count: addedCount
            });

            // 延时关闭并跳转
            setTimeout(() => {
              this.closePopup();
              wx.switchTab({
                url: '/pages/photo/photo',
              });
            }, 2000);
          }
        })
        .catch(err => {
          console.log("激活失败", err);
          // 激活失败
          this.setData({
            resultType: 'error',
            resultMessage: err.msg || '激活失败，请重试'
          });

          wx.showToast({
            title: err.msg || '激活失败',
            icon: 'none'
          });
        })
        .finally(() => {
          wx.hideLoading();
          this.setData({
            isActivating: false
          });
        });
    },

    // 阻止点击蒙层关闭
    preventClose() {
      return false;
    },

    // 确保用户已登录
    ensureLogin() {
      const app = getApp();
      if (!app.checkLoginStatus()) {
        app.userLogin();
      }
    }
  }
}); 